#!/bin/bash

if type -p java; then
    echo "Found Java executable in PATH."
    _java=java
elif [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]] ; then
    echo "Found Java executable in JAVA_HOME."     
    _java="$JAVA_HOME/bin/java"
else
    echo "No Java found. Download the latest JDK."
    exit 0;
fi

if [[ "$_java" ]] ; then
    version=$("$_java" -version 2>&1 | awk -F '"' '/version/ {print $2}')
    echo version "$version"
    if [[ "$version" < "1.7" ]]; then
        echo "Version is less than 1.7."
        exit 0;
    fi
fi

if [ ! -f "local.properties" ] && [ -z "${ANDROID_HOME+x}" ] ; then
    echo "File local.properties not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable."
    exit 0;
fi

if [ -z "${ANDROID_HOME+x}" ] ; then
    ANDROID_HOME=$(grep sdk.dir local.properties | cut -d= -f2)
fi

echo install tools
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "tools"
echo "tools done"
echo "install build-tools"
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "build-tools;26.0.3"
echo "build-tools done"
echo "install android-26"
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "platforms;android-26"
echo "android-26 done"
echo "install android m2repository"
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "extras;android;m2repository"
echo "android m2repository done"
echo "install google m2repository"
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "extras;google;m2repository"
echo "google m2repository done"
echo "install constraint-layout"
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "extras;m2repository;com;android;support;constraint;constraint-layout;1.0.2"
echo "constraint-layout done"
echo "install constraint-layout-solver"
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.2"
echo "constraint-layout-solver done"
echo "install system-images"
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "system-images;android-26;google_apis;x86"
echo "system-images done"

echo "Create emulator"
echo no | $ANDROID_HOME/tools/bin/avdmanager create avd -n test -k "system-images;android-26;google_apis;x86" -f --abi "x86" --tag "google_apis"
echo "Emulator created"
echo "Start emulator"
$ANDROID_HOME/emulator/emulator -avd test $1 &

echo "Clean project"
./gradlew clean
./android-wait-for-emulator $ANDROID_HOME
echo "Emulator started"
echo "Start building tests"
./gradlew :sample:connectedAndroidTest -PdisablePreDex --info
$ANDROID_HOME/platform-tools/adb emu kill
